#include "rpc_param.h"
#include <mysql/mysql.h>
#include <my_global.h>

extern MYSQL *myconn;
MYSQL_RES *myresult;
MYSQL_ROW myrow;

bool_t
query_1_svc(char **argp, char **result, struct svc_req *rqstp) {
	char *buf = (char *) malloc(1000000 * sizeof(char));
	int numfields;
	int idx = 0;				
	int i;
	
	// Imprime qual cliente esta fazendo a requisicao e qual requisicao esta sendo feita
	printf("%s: %s\n",((struct authunix_parms *) rqstp->rq_clntcred)->aup_machname, *argp);
	fflush(stdout);
	

	if (mysql_query(myconn, *argp) != 0) {
		fprintf(stderr, "query falhou.\n");
		free(buf);
		exit(1);
	}
	
	// executa a query requisitada pelo cliente	
	myresult = mysql_store_result(myconn);
	if (myresult != NULL) {
		numfields = mysql_num_fields(myresult);
		while ((myrow = mysql_fetch_row(myresult))) {
			for (i = 0; i < numfields; i++){
				idx += sprintf(&buf[idx], "%s | ", myrow[i] ? myrow[i] : "NULL");
			}
			idx -= 3; 
			buf[idx++] = '\n';
			*result = buf;
		}
		buf[idx] = '\0';
		*result = buf;
	} else {
		strcpy(buf, "NULL");
		*result = buf;
	} 
	mysql_free_result(myresult);
	return TRUE;
}

int rpc_param_prog_1_freeresult(SVCXPRT * transp, xdrproc_t xdr_result, caddr_t result) {
	xdr_free(xdr_result, result);
	return 1;
}
